# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import codecs
import datetime
import json
import os
import threading
import time
from random import randint, choice, uniform

import pyautogui
import requests
import simpleaudio as sa
from dateutil.parser import parse
from lunardate import LunarDate
from pydub import AudioSegment
from pydub.playback import play



def create_directories(empty_dirs):
    # 创建空文件夹
    if empty_dirs:
        for empty_dir in empty_dirs:
            if not os.path.exists(empty_dir):
                os.makedirs(empty_dir)
                print(f"创建空文件夹: {empty_dir}")


def add_random_data():
    # print("生成随机用户")
    data = {
        "username": f'user_{int(time.time())}',
        "details": {
            "types": "随机",
            "content": str(generate_random_date())[:-9]
        },
        "pars_date": {}
    }
    return data




def start_thread(thread, *args):
    hotkey_thread = threading.Thread(target=thread, args=args)
    hotkey_thread.start()  # 启动线程
    return hotkey_thread  # 返回线程对象，以便后续操作


def press_keys(keys):
    """按下指定的键"""
    for t in keys:
        pyautogui.press(t)
        time.sleep(uniform(0.1, 0.2))


def read_json(file):
    if os.path.exists(file) and os.path.getsize(file) > 0:
        with codecs.open(file, 'r', encoding='utf-8') as f:
            data = json.load(f)  # 读取 JSON 数据
        return data



def format_day(data):
    try:
        date = parse(data, fuzzy=True)  # 尝试解析日期
        if isinstance(date, datetime.datetime):  # 检查 date 是否为 datetime 类型
            print(f"解析成功，日期为: {date}")
    except Exception as e:
        print(f"解析失败，错误信息: {e}")
        return False
    if date:
        year = date.year
        month = date.month
        day = date.day
        now_year = datetime.datetime.now().date().year
        if (year < 1950 or year > now_year or month < 1 or month > 12 or day < 1 or day > 31):
            return False
        # 直接使用解析后的日期对象
        OK_date = date.strftime('%Y%m%d')
        format_date = date.strftime('%Y年%m月%d日')  # 格式化为中文日期
        # 转换农历日期
        lunar_date = LunarDate.fromSolarDate(int(year), int(month), int(day))
        lunar_year = str(lunar_date.year).zfill(4)  # 年份补齐4位
        lunar_month = str(lunar_date.month).zfill(2)  # 月份补齐2位
        lunar_day = str(lunar_date.day).zfill(2)  # 日补齐2位
        lunar_date = f'{lunar_year}年{lunar_month}月{lunar_day}日'
        # 计算生肖
        zodiacs = ["鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"]
        start_year = 1900  # 农历生肖起始年份为1900年（鼠年）
        wuxing=wuxingjiazi(year)
        zodiac = f"{wuxing}{zodiacs[(year - start_year) % 12]}"  # 生肖
        # 生成随机数
        rdm = randint(70, 100)
        # 使用lambda表达式表示条件逻辑
        color = (lambda x: "red" if x >= 90 else "green" if x >= 75 else "black")(rdm)
        data = {

                "OK_date": OK_date,
                "format_date": format_date,
                "lunar_date": lunar_date,
                "zodiac": zodiac,
                "rdm": rdm,
                "color": color,
                "year": year,
                "month": month,
                "day": day,

        }
        # print(f"---------------: {data}")
        return data



def wuxingjiazi(year):
    tiangan = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸']
    dizhi = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥']
    # 计算天干和地支索引
    t_index = (year - 4) % 10
    d_index = (year - 4) % 12
    # 获取天干和地支
    tg = tiangan[t_index]
    dz = dizhi[d_index]
    # 获取五行
    if tg in ['甲', '乙']:
        wuxing = '木'
    elif tg in ['丙', '丁']:
        wuxing = '火'
    elif tg in ['戊', '己']:
        wuxing = '土'
    elif tg in ['庚', '辛']:
        wuxing = '金'
    elif tg in ['壬', '癸']:
        wuxing = '水'

    return wuxing

    # return f"{tg}{dz} ({wuxing})"





def generate_random_date(start_year=1950, end_year=2004):
    # 定义起始日期和结束日期
    start_date = datetime.datetime(start_year, 1, 1)
    end_date = datetime.datetime(end_year, datetime.datetime.now().month, datetime.datetime.now().day)
    # 计算日期范围内的天数差
    delta_days = (end_date - start_date).days
    # 生成随机天数
    random_days = randint(0, delta_days)
    # 计算随机日期
    random_date = start_date + datetime.timedelta(days=random_days)
    return random_date



def update_json(file_path, updates):
    if not os.path.exists(file_path):
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(updates, file, ensure_ascii=False, indent=4)
            return
    # 读取现有的JSON数据
    with open(file_path, 'r', encoding='utf-8') as file:
        data = json.load(file)
    # 使用update方法更新数据
    data.update(updates)
    # 将更新后的数据写回文件
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data, file, ensure_ascii=False, indent=4)






def update_list(data_list, update_content):
    def recursive_update(original, updates):
        for key, value in updates.items():
            if isinstance(value, dict) and key in original and isinstance(original[key], dict):
                recursive_update(original[key], value)
            else:
                original[key] = value

    updated = False
    for item in data_list:
        if item.get('username') == update_content.get('username'):
            recursive_update(item, update_content)
            updated = True
            break

    if not updated:
        data_list.append(update_content)

def update_jsons(file_path, update_content):
    # 检查文件是否存在
    if not os.path.exists(file_path):
        # 如果文件不存在，则创建一个新的空列表并写入文件
        with open(file_path, 'w', encoding='utf-8') as f:
            json.dump([], f, ensure_ascii=False, indent=4)

    def recursive_update(original, updates):
        for key, value in updates.items():
            if isinstance(value, dict) and key in original and isinstance(original[key], dict):
                # 如果值是字典且在原始字典中存在，则递归更新
                recursive_update(original[key], value)
            else:
                # 否则直接更新或新增
                original[key] = value

    # 读取现有的JSON数据
    with open(file_path, 'r', encoding='utf-8') as f:
        data = json.load(f)

    # 更新数据
    updated = False
    for item in data:
        if item.get('username') == update_content.get('username'):
            # 递归更新字典中的键值对
            recursive_update(item, update_content)
            updated = True
            break

    # 如果没有找到匹配的username，则添加新的字典
    if not updated:
        data.append(update_content)

    # 将更新后的数据写回文件
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)



def play_audios(file_1, file_2, file_3, file_4):
    # 加载音频文件
    audio_a = AudioSegment.from_file(file_1)
    audio_b = AudioSegment.from_file(file_2)
    audio_c = AudioSegment.from_file(file_3)
    audio_d = AudioSegment.from_file(file_4)
    # 计算 D 的开始时间（与 A 同步开始）
    # 叠加 D 到 A
    combined_a_d = audio_a.overlay(audio_d)
    # 播放叠加后的 A 和 D
    play(combined_a_d)
    # 播放 B，同时将 D 叠加到 B
    combined_b_d = audio_b.overlay(audio_d)
    play(combined_b_d)
    # 播放 C，同时将 D 叠加到 C
    combined_c_d = audio_c.overlay(audio_d)
    play(combined_c_d)









def play_audio(file):
    # 播放指定文件
    audio = AudioSegment.from_file(file)
    # 将音频转换为简单音频格式
    samples = audio.get_array_of_samples()
    # 创建一个简单音频对象
    play_obj = sa.play_buffer(samples, num_channels=audio.channels,
                              bytes_per_sample=audio.sample_width,
                              sample_rate=audio.frame_rate)
    # 等待音频播放完成
    play_obj.wait_done()


def players(path, s=0):
    # 随机播放
    # 加载选定的WAV文件
    audio = AudioSegment.from_file(f'{path}/{choice(os.listdir(path))}')
    # 降低音量
    quieter_audio = audio - s
    # 保存降低音量后的音频文件
    quieter_audio.export(('audio/output.wav'), format='wav')
    # 加载音频文件
    play_obj = sa.WaveObject.from_wave_file(('audio/output.wav')).play()
    # 等待音频播放完成
    play_obj.wait_done()






def class_json(file, data=None):
    # print("清空json")
    with open(file, 'w', encoding='utf-8') as json_file:
        json.dump(data, json_file, ensure_ascii=False, indent=4)



def class_text(file, data=None):
    # 检查文件是否存在
    if not os.path.exists(file):
        with open(file, 'w', encoding='utf-8') as f:
            f.write(data)




def reset_json(file, data=None):
    if not os.path.exists(file):
        with open(file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=4)




def get_url(url, params=None,headers=None):
    try:
        response = requests.get(url, params=params,headers=headers)
        response.raise_for_status()  # 检查请求是否成功
        return response.json()  # 返回JSON响应数据
    except requests.exceptions.HTTPError as http_err:
        print(f"HTTP错误: {http_err}")
    except Exception as err:
        print(f"其他错误: {err}")
    return None


def get_latest_version():
    UPDATE_URL = 'https://gitee.com/liang_shanshui/dyage/raw/master/version.txt'
    try:
        # 发送 GET 请求获取文件内容
        response = requests.get(UPDATE_URL)
        response.raise_for_status()  # 检查请求是否成功
        latest_version = response.text.strip()  # 获取版本号并去除多余空格
        return latest_version
    except requests.exceptions.RequestException as e:
        print(f"获取最新版本时出错: {e}")
        return None